package org.springframework.samples.petclinic.web;

import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.samples.petclinic.model.Alien;
import org.springframework.samples.petclinic.model.Owner;
import org.springframework.samples.petclinic.service.ClinicService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes(types = Alien.class)
public class AlienController {

    private final ClinicService clinicService;
    private static Logger logger = LoggerFactory.getLogger(AlienController.class);

    @Autowired
    public AlienController(ClinicService clinicService) {
        this.clinicService = clinicService;
    }

    @InitBinder
    public void setAllowedFields(WebDataBinder dataBinder) {
        dataBinder.setDisallowedFields("id");
    }

    @RequestMapping(value = "/aliens/new", method = RequestMethod.GET)
    public String initCreationForm(Map<String, Object> model) {
        Alien owner = new Alien();
        model.put("owner", owner);
        return "aliens/createOrUpdateAlienForm";
    }

    @RequestMapping(value = "/aliens/new", method = RequestMethod.POST)
    public String processCreationForm(@Valid Alien owner, BindingResult result, SessionStatus status) throws InterruptedException {
        if (result.hasErrors()) {
            return "aliens/createOrUpdateAlienForm";
        } else {
            owner.setThreadId(Thread.currentThread().getId());
            for (int i = 1; i <= owner.getSeries(); i++) {
                owner.setSeriesNo(i);
                this.clinicService.saveAlien(owner);
                logger.info("finished series " + i + " " + owner);
                if (owner.getAfterSeriesSleep() > 0) {
                    Thread.sleep(owner.getAfterInsertSleep());
                }
                
                if (i < owner.getSeries()) {
                    owner.setId(null);
                }
            }
            
            status.setComplete();
            return "redirect:/owners/" + owner.getId();
        }
    }
}
